package com.travelsky.server.chat_socket;

import java.util.ArrayList;
import java.util.List;

/**
 * 代码提交工具-服务器端广播类
 ******************************************
 * @author HuangFeng  [2017年7月5日 下午12:43:10]
 * @version 1.0
 ******************************************
 */
public class BroadCast extends Thread {

	/**
	 * 客户端线程
	 */
	private ClientThread clientThread;
	
	/**
	 * 服务器端线程
	 */
	private ServerThread serverThread;
	
	/**
	 * 消息
	 */
	private String str;
	
	/**
	 * 退出标志
	 */
	private boolean flag_exit = false;
	
	/**
	 * 构造方法
	 ******************************************
	 * @author HuangFeng [2017年7月5日 下午12:45:04]
	 * @version 1.0
	 ******************************************
	 * @param serverThread 服务器线程
	 */
	public BroadCast(ServerThread serverThread){
		this.serverThread = serverThread;
	}
	
	@Override
	public void run() {
		List<ClientThread> lostConnection = new ArrayList<ClientThread>();
		while (flag_exit) {
			try {
				//睡眠一会，减少CPU占用率
				sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (serverThread.messages.isEmpty()) {
				continue;
			} else {
				str = (String) serverThread.messages.firstElement();
				serverThread.messages.removeElement(str);
			}
			try {
				if (str.contains("@single")) {
					String[] info = str.split("@single");
					int id_thread = Integer.parseInt(info[2]);
					for (int j = 0; j < serverThread.clients.size(); j++) {
						clientThread = serverThread.clients.elementAt(j);
						if (id_thread == clientThread.getId()) {
							clientThread.dos.writeUTF(str);
							break;
						}
					}
				}else{
					// 向纪录的每一个客户端发送数据信息
					for (int i = 0; i < serverThread.clients.size(); i++) {
						try {
							clientThread = serverThread.clients.elementAt(i);
							clientThread.dos.writeUTF(str);
						} catch (Exception e) {
							//如果socket断开连接了，就清除掉
							lostConnection.add(clientThread);
						}
					}
				}
			} catch (Exception E) {
				//如果socket断开连接了，就清除掉
				lostConnection.add(clientThread);
			}
			if (str.contains("@serverexit")) {
				serverThread.stopServerThread();
				break;
			}
			serverThread.clearLostConnection(lostConnection);
		}
	}
	
	public void setFlag_exit(boolean b) {
		flag_exit = b;
	}

}
